package com.yuda.tools.log.controller;


import com.alibaba.fastjson.JSON;
import com.yuda.common.core.constant.HttpStatus;
import com.yuda.common.core.web.controller.BaseController;
import com.yuda.common.core.web.page.PageDomain;
import com.yuda.common.core.web.page.TableDataInfo;
import com.yuda.common.core.web.page.TableSupport;
import com.yuda.tools.log.entity.AnswerForTianKong;
import com.yuda.tools.log.entity.LogInfo;
import com.yuda.tools.log.service.LogService;
import com.yuda.tools.log.utils.DownFile;
import com.yuda.tools.log.utils.ExcelUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

@RestController
public class LogController extends BaseController {

    public static final Logger logger = LoggerFactory.getLogger(LogController.class);
    @Autowired
    private LogService logService;
    private String rootDir = "";//是否为windows

    @GetMapping("/allLog")
    public TableDataInfo getAll(@RequestParam(value = "studentId", required = false) String studentId,
                                @RequestParam(value = "sfzNum", required = false) String sfzNum,
                                @RequestParam(value = "zkzNum", required = false) String zkzNum,
                                @RequestParam(value = "studentName", required = false) String studentName,
                                @RequestParam(value = "pcNo", required = false) String pcNo) {


        List<LogInfo> allLogList = logService.getAllLog(studentId, sfzNum, zkzNum, studentName, pcNo);

        List<LogInfo> NewAllList = new ArrayList<>();

        for (LogInfo logInfo : allLogList) {
            String use = "";
            LogInfo New_logInfo = new LogInfo();

            New_logInfo.setId(logInfo.getId());
            New_logInfo.setLogId(logInfo.getLogId());
            New_logInfo.setStudentId(logInfo.getStudentId());
            New_logInfo.setQuesId(logInfo.getQuesId());
            New_logInfo.setStatType(logInfo.getStatType());


            if (logInfo.getQuesIndex() != 0) {
                New_logInfo.setQuestionNo(logInfo.getQuesIndex());
            }
            New_logInfo.setSubjectName(logInfo.getSubjectName());

            if (!StringUtils.isEmpty(logInfo.getRelSubjectName())) {
                New_logInfo.setRelSubjectName(logInfo.getRelSubjectName());
            } else {
                if (!(logInfo.getSubjectRelationId().equals(0))) {
                    New_logInfo.setRelSubjectName(use);//加时
                }
            }

            String str = "";
            if (logInfo.getStatType() == 0) {
                str = "登录";
            } else if (logInfo.getStatType() == 1) {
                str = "开考";
            } else if (logInfo.getStatType() == 2) {
                str = "填入答案";
            } else if (logInfo.getStatType() == 3) {
                str = "进入该题";
            } else if (logInfo.getStatType() == 4) {
                str = "离开该题";
            } else if (logInfo.getStatType() == 5) {
                if (logInfo.getQuesId() == 1) {
                    str = "倒计时结束自动交卷";
                } else if (logInfo.getQuesId() == 0) {
                    str = "主动交卷";
                }
            } else if (logInfo.getStatType() == 6) {
                str = logInfo.getMsg();
            } else if (logInfo.getStatType() == 7) {
                str = "离开选题";
            } else if (logInfo.getStatType() == 8) {
                str = "进入选题界面";
            }

            New_logInfo.setStatTypeStr(str);
            New_logInfo.setTime(logInfo.getTime());
            String answerABC = logInfo.getAnswerAbc();

            if (logInfo.getQuesId() != 0 && answerABC != null && !"".equals(answerABC)) {
                if (answerABC.startsWith("[")) {
                    List<AnswerForTianKong> tianKongList = JSON.parseArray(answerABC, AnswerForTianKong.class);
                    StringBuffer tkStr = new StringBuffer();
                    for (AnswerForTianKong tk : tianKongList) {
                        tkStr.append(tk.getAnswer());
                    }
                    New_logInfo.setAnswerAbc(tkStr.toString());

                } else if(logInfo.getSubjectRelationId().equals("1002")) {
                    if(logInfo.getAnswerAbc().endsWith("#")) {
                        New_logInfo.setAnswerAbc(logInfo.getAnswerAbc().substring(0,logInfo.getAnswerAbc().length()-1));
                    }

                } else {
                    New_logInfo.setAnswerAbc(toABC(logInfo.getAnswerAbc()));
                }
            } else {
                New_logInfo.setAnswerAbc(logInfo.getAnswerAbc());
            }
            New_logInfo.setPcNo(logInfo.getPcNo());
            NewAllList.add(New_logInfo);
        }

        //自定义分页
        int total = NewAllList.size();
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        int fromIndex = (pageNum - 1) * pageSize;
        if (fromIndex > total) {
            int yuShu = total % pageSize;
            NewAllList = NewAllList.subList(total - yuShu, total);
        } else {
            int toIndex = pageNum * pageSize;
            if (toIndex > total) {
                toIndex = total;
            }
            NewAllList = NewAllList.subList(fromIndex, toIndex);
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(NewAllList);
        rspData.setMsg("查询成功");
        rspData.setTotal(total);

        for (LogInfo logInfo : NewAllList) {
            System.out.println(logInfo);
        }
        return rspData;
    }

    @GetMapping("/allPcNo")
    public List<Integer> getAllPcNo(@RequestParam(value = "studentId", required = false) String studentId,
                                    @RequestParam(value = "sfzNum", required = false) String sfzNum,
                                    @RequestParam(value = "zkzNum", required = false) String zkzNum) {

        List<Integer> PcNoList = logService.getPcNoList(studentId, sfzNum, zkzNum);
        return PcNoList;

    }


    @GetMapping(value = "/exportData")
    @ResponseBody
    //Map<String, Object>
    public void exportData(@RequestParam(value = "studentId", required = false) String studentId,
                           @RequestParam(value = "sfzNum", required = false) String sfzNum,
                           @RequestParam(value = "zkzNum", required = false) String zkzNum,
                           @RequestParam(value = "studentName", required = false) String studentName,
                           @RequestParam(value = "pcNo", required = false) String pcNo,
                           HttpServletRequest request, HttpServletResponse response) {

        List<LogInfo> allLogList = logService.getAllLog(studentId, sfzNum, zkzNum, studentName, pcNo);

        if (studentId == null && allLogList.size() != 0) {
            studentId = allLogList.get(0).getStudentId();
        }

        List<String[]> logs = new ArrayList<>();
        Map<String, String> map = new LinkedHashMap<>();
        map.put("time", "时间");
        map.put("pcNo", "机座号");
        map.put("subjectName", "科目");
        map.put("relSubjectName", "关联科目");
        map.put("quesId", "题目ID");
        map.put("questionNo", "题号");
        map.put("statTypeStr", "操作");
        map.put("answerAbc", "信息");
        map.put("result", "结果");

        List<LogInfo> list = new ArrayList<>();
        for (LogInfo logInfo : allLogList) {
            String use = "";
            LogInfo New_logInfo = new LogInfo();

            New_logInfo.setStudentId(logInfo.getStudentId());
            New_logInfo.setQuesId(logInfo.getQuesId());
            New_logInfo.setStatType(logInfo.getStatType());
            if (logInfo.getQuesIndex() != 0) {
                New_logInfo.setQuestionNo(logInfo.getQuesIndex());
            }
            New_logInfo.setSubjectName(logInfo.getSubjectName());

            if (!StringUtils.isEmpty(logInfo.getRelSubjectName())) {
                New_logInfo.setRelSubjectName(logInfo.getRelSubjectName());
            } else {
                if (!(logInfo.getSubjectRelationId().equals(0))) {
                    New_logInfo.setRelSubjectName(use);//加时
                }
            }

            String str = "";
            if (logInfo.getStatType() == 0) {
                str = "登录";
            } else if (logInfo.getStatType() == 1) {
                str = "开考";
            } else if (logInfo.getStatType() == 2) {
                str = "填入答案";
            } else if (logInfo.getStatType() == 3) {
                str = "进入该题";
            } else if (logInfo.getStatType() == 4) {
                str = "离开该题";
            } else if (logInfo.getStatType() == 5) {
                if (logInfo.getQuesId() == 1) {
                    str = "倒计时结束自动交卷";
                } else if (logInfo.getQuesId() == 0) {
                    str = "主动交卷";
                }
            } else if (logInfo.getStatType() == 6) {
                str = logInfo.getMsg();
            } else if (logInfo.getStatType() == 7) {
                str = "离开选题";
            } else if (logInfo.getStatType() == 8) {
                str = "进入选题界面";
            }

            New_logInfo.setStatTypeStr(str);
            New_logInfo.setTime(logInfo.getTime());
            String answerABC = logInfo.getAnswerAbc();

            if (logInfo.getQuesId() != 0 && answerABC != null && !"".equals(answerABC)) {
                if (answerABC.startsWith("[")) {
                    List<AnswerForTianKong> tianKongList = JSON.parseArray(answerABC, AnswerForTianKong.class);
                    StringBuffer tkStr = new StringBuffer();
                    for (AnswerForTianKong tk : tianKongList) {
                        tkStr.append(tk.getAnswer());
                    }
                    New_logInfo.setAnswerAbc(tkStr.toString());
                } else {
                    New_logInfo.setAnswerAbc(toABC(logInfo.getAnswerAbc()));
                }
            } else {
                New_logInfo.setAnswerAbc(logInfo.getAnswerAbc());
            }
            New_logInfo.setPcNo(logInfo.getPcNo());
            list.add(New_logInfo);
        }


        String xiTong = System.getProperty("os.name");
        if (xiTong.toUpperCase().startsWith("WIN")) {
            //rootDir = request.getSession().getServletContext().getRealPath("/");
            try {
                rootDir = ResourceUtils.getURL("classpath:").getPath() + "static/file/";
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        } else {
            rootDir = "/home/dbLog/";//linux
        }

        String sepatetor = System.getProperty("file.separator");
        File folder = new File(rootDir + sepatetor + "logexcel");
        if (!folder.exists() && !folder.isDirectory()) {
            folder.mkdirs();
        }
        File file = new File(rootDir + "logexcel" + sepatetor + studentId + "_logs.xlsx");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        response.setContentType("application/vnd.ms-excel;chalogInfoet=utf-8");
        try {
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(studentId + "_log.xlsx", "UTF-8"));
            FileOutputStream fos = null;
            fos = new FileOutputStream(file.getAbsolutePath());
            ExcelUtil.export(list, fos, map);
            result.put("code", 1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //String root = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();
        //String path = rootDir+"logexcel"+sepatetor+studentId+"_logs.xlsx";
        //String path = "file/"+"logexcel"+sepatetor+studentId+"_logs.xlsx";

        String path = file.getAbsolutePath();
        System.out.println(path);
		/*if(xiTong.toUpperCase().startsWith("WIN") ) {
			path = "file/"+"logexcel"+sepatetor+studentId+"_logs.xlsx";
		} else {
			path = "dbLog"+sepatetor+"logexcel"+sepatetor+studentId+"_logs.xlsx";
		}

		result.put("result", path);
		return result;*/

        logger.info("成功导出文件path: " + path);
        List<File> srcFiles = new ArrayList<File>();
        srcFiles.add(new File(path));

        String filename = studentId + "_log";
        logger.info("成功导出文件： " + filename);
        DownFile.setResponseHeader(response, filename);
        try {
            DownFile.toZip(srcFiles, response.getOutputStream());
        } catch (RuntimeException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public String toABC(String str) {
        char[] chars = str.toCharArray();
        StringBuffer sb = new StringBuffer();
        if (chars[0] == '-') {
            return "未答";
        }
        for (char c : chars) {
            switch (c) {
                case '1':
                    sb.append("A");
                    break;
                case '2':
                    sb.append("B");
                    break;
                case '3':
                    sb.append("C");
                    break;
                case '4':
                    sb.append("D");
                    break;
                case '5':
                    sb.append("E");
                    break;
                case '6':
                    sb.append("F");
                    break;
                case '7':
                    sb.append("G");
                    break;
                case '8':
                    sb.append("H");
                    break;
                case '#':
                    sb.append("#");
                    break;
            }
        }
        return sb.toString();
    }


}
